package com.bang.study.day03.heap;

import com.alibaba.fastjson.JSONObject;
import com.bang.study.day01.list.Array;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Auther: Bang
 * @Date: 2019/9/14 23:04
 * @Description: 动态数组实现最大堆
 */
public class MaxHeap<E extends Comparable<E>> {

    private Array<E> data;

    public MaxHeap() {
        this.data = new Array<>();
    }

    public MaxHeap(E[] arr) {
        this.data = new Array<>(arr);
        for (int i = parent(arr.length - 1); i >= 0; i--) {
            siftDown(i);
        }
    }

    /**
     * 堆的大小
     *
     * @return
     */
    public int getSize() {
        return data.getSize();
    }

    /**
     * 堆是否为空
     *
     * @return
     */
    public boolean isEmpty() {
        return data.isEmpty();
    }


    /**
     * 向堆中添加元素
     *
     * @param e
     */
    public void add(E e) {
        data.addLast(e);
        siftUp(data.getSize() - 1);
    }

    /**
     * 当前index在堆中上移
     *
     * @param k
     */
    private void siftUp(int k) {
        while (k > 0 && data.get(parent(k)).compareTo(data.get(k)) < 0) {
            data.swap(k, parent(k));
            k = parent(k);
        }
    }

    /**
     * 查找堆中最大元素
     *
     * @return
     */
    public E findMax() {
        if (data.getSize() == 0) {
            throw new IllegalArgumentException("Can not findMax when heap is empty.");
        }
        return data.get(0);
    }

    /**
     * 取出堆中最大元素
     *
     * @return
     */
    public E extractMax() {
        E max = findMax();
        // 交换根节点和最后一个元素
        data.swap(0, data.getSize() - 1);
        // 移除最后一个元素
        data.removeLast();
        // root元素下沉
        siftDown(0);
        return max;
    }

    /**
     * 将index下沉
     *
     * @param index
     */
    private void siftDown(int index) {
        int size = data.getSize();
        while (leftChild(index) < size) {
            // 在此轮循环中,data[swap]和data[index]交换位置
            int swap = leftChild(index);
            if (swap + 1 < size && data.get(swap).compareTo(data.get(swap + 1)) < 0) {
                // 有右节点 且右节点大于左节点
                swap = swap + 1;
            }
            if (data.get(index).compareTo(data.get(swap)) >= 0) {
                break;
            }
            data.swap(swap, index);
            index = swap;
        }
    }

    /**
     * 替换堆上的元素
     *
     * @param e
     * @return
     */
    public E replace(E e) {
        E max = findMax();
        data.set(0, e);
        siftDown(0);
        return max;
    }

    /**
     * 返回index的父亲节点的index
     *
     * @param index
     * @return
     */
    private int parent(int index) {
        if (index == 0) {
            throw new IllegalArgumentException("index-0 doesn't have parent.");
        } else {
            return (index - 1) / 2;
        }
    }

    /**
     * 返回index的左孩子节点的index
     *
     * @param index
     * @return
     */
    private int leftChild(int index) {
        return index * 2 + 1;
    }

    /**
     * 返回index的友孩子节点的index
     *
     * @param index
     * @return
     */
    private int rightChild(int index) {
        return index * 2 + 2;
    }

    @Override
    public String toString() {
        return "MaxHeap{" +
                "data=" + JSONObject.toJSONString(data) +
                '}';
    }

    public static void main(String[] args) {
        MaxHeap<Integer> maxHeap = new MaxHeap<>();
        Random random = new Random();
        int size = 100000;
        for (int i = 0; i < size; i++) {
            maxHeap.add(random.nextInt(Integer.MAX_VALUE));
        }
        List<Integer> list = new ArrayList();
        while (!maxHeap.isEmpty()) {
            list.add(maxHeap.extractMax());
        }

        int size1 = list.size();
        for (int i = 1; i < size1; i++) {
            if (list.get(i - 1) < list.get(i)) {
                throw new RuntimeException("TEST FAIL");
            }
        }
        System.out.println("SUCCESS");

    }
}
